<template>
  <div class="avatar-setting-container">
    <!-- 页面标题 -->
    <div class="page-header" >
      <h2 style="font-size: 12px;">アバターを設定する</h2>
    </div>

    <!-- 头像设置内容 -->
    <div class="avatar-content">
      <!-- 左右布局 -->
      <div class="content-layout">
        <!-- 左侧标签 -->
        <div class="left-section">
          <div class="profile-label">プロフィール</div>
          <div class="upload-label">画像を設定:</div>
        </div>
        
        <!-- 右侧上传区域 -->
        <div class="right-section">
          <div class="upload-box" @click="triggerUpload">
            <div v-if="!avatarPreview" class="upload-placeholder">
              <el-icon class="upload-icon"><Plus /></el-icon>
            </div>
            <img v-else :src="avatarPreview" class="avatar-preview" alt="头像预览" />
          </div>
          
          <!-- 隐藏的文件上传输入 -->
          <input 
            ref="fileInput" 
            type="file" 
            accept="image/*" 
            @change="handleFileSelect" 
            style="display: none;"
          />
        </div>
      </div>

      <!-- 提交按钮 -->
      <div class="submit-section">
        <el-button 
          type="primary" 
          size="large" 
          class="submit-btn"
          :loading="uploading"
          @click="submitAvatar"
        >
          送信
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { userApi, commonApi, BASE_URL } from '../../../api/index'

const router = useRouter()
const fileInput = ref(null)
const avatarPreview = ref('')
const uploading = ref(false)
const selectedFile = ref(null)

// 触发文件选择
const triggerUpload = () => {
  fileInput.value?.click()
}

// 处理文件选择
const handleFileSelect = (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  // 验证文件类型
  const isImage = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg'].includes(file.type)
  if (!isImage) {
    ElMessage.error('请选择图片格式的文件!')
    return
  }
  
  // 验证文件大小（小于2MB）
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('画像のサイズは2MBを超えてはいけません。!')
    return
  }
  
  selectedFile.value = file
  
  // 创建预览
  const reader = new FileReader()
  reader.onload = (e) => {
    avatarPreview.value = e.target.result
  }
  reader.readAsDataURL(file)
}

// 提交头像
const submitAvatar = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('画像を選択してください。')
    return
  }
  
  try {
    uploading.value = true
    
    // 显示加载中
    const loadingInstance = ElLoading.service({
      lock: true,
      text: 'アイコンがアップロード中です。',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    
    // 上传文件
    const uploadRes = await commonApi.upload(selectedFile.value)
    
    if (uploadRes.code === 1 && uploadRes.data) {
      // 更新用户头像信息
      const updateRes = await userApi.updateAvatar({
        avatar: uploadRes.data.url
      })
      
      if (updateRes.code === 1) {
        ElMessage.success('アイコンの変更が成功しました。')
        // 返回上一页或跳转到个人信息页
        router.back()
      } else {
        ElMessage.error(updateRes.msg )
      }
    } else {
      ElMessage.error(uploadRes.msg )
    }
    
    loadingInstance.close()
  } catch (error) {
    console.error('アイコンのアップロードに失敗しました:', error)
    ElMessage.error('アイコンのアップロードに失敗しました。')
  } finally {
    uploading.value = false
  }
}
</script>

<style scoped>
.avatar-setting-container {
  max-width: 550px;
  margin-top: 30px;
  margin-left: 300px;
  padding: 20px;
  background-color: #ffffff;
  /* min-height: 50vh; */
  max-height: 323px;
  box-shadow: rgba(0, 0, 0, 0.12) 0px 0px 12px 0px;
}

.page-header {
  margin-bottom: 20px;
  position: relative;
  top: -25px;
}

.page-header h2 {
  font-size: 20px;
  font-weight: 400;
  color: #333;
  margin: 0;
  padding: 20px 0;
  border-bottom: 1px solid #e0e0e0;
}

.avatar-content {
  /* height: 200px; */
  background-color: white;
  border-radius: 8px;
  padding: 10px;
  /* box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); */
  position: relative;
  top: -40px;
  
}

.content-layout {
  display: flex;
  align-items: flex-start;
  gap: 40px;
  margin-bottom: 40px;
}

.left-section {
  flex-shrink: 0;
  width: 150px;
}

.profile-label {
  font-size: 12px;
  font-weight: 400;
  color: #333;
  margin-bottom: 20px;
}

.upload-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 0;
}

.right-section {
  flex: 1;
  display: flex;
  justify-content: flex-start;
}

.upload-box {
  width: 170px;
  height: 180px;
  border: 2px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: border-color 0.3s;
  overflow: hidden;
  background-color: #fafafa;
  position: relative;
  right: 80px;
  top: -10px;
}

.upload-box:hover {
  border-color: #409eff;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #999;
}

.upload-icon {
  font-size: 48px;
  color: #c0c4cc;
}

.avatar-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.submit-section {
  margin-top: -30px;
  display: flex;
  justify-content: center;
}

.submit-btn {
  width: 100%;
  height: 44px;
  font-size: 16px;
  border-radius: 4px;
  background-color: #4A90E2;
  border-color: #4A90E2;
}

.submit-btn:hover {
  background-color: #357ABD;
  border-color: #357ABD;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .avatar-setting-container {
    max-width: 100%;
    margin: 20px auto;
    margin-left: auto;
    margin-right: auto;
    padding: 15px;
    position: relative;
    left: auto;
    transform: none;
    max-height:380px;
  }
  
  .page-header {
    margin-bottom: 15px;
  }
  
  .page-header h2 {
    font-size: 18px;
    padding: 15px 0;
  }
  
  .avatar-content {
    padding: 20px 15px;
  }
  
  .content-layout {
    flex-direction: column;
    gap: 20px;
    margin-bottom: 5px;
  }
  
  .left-section {
    width: 100%;
    text-align: center;
  }
  
  .profile-label {
    font-size: 15px;
    margin-bottom: 15px;
  }
  
  .upload-label {
    font-size: 13px;
    margin-bottom: 15px;
  }
  
  .right-section {
    display: flex;
    justify-content: center;
    width: 100%;
  }
  
  .upload-box {
    width: 50%;
    max-width: 300px;
    height: 100px;
    margin: 0 auto;
    position: relative;
    right: 0px;
    display: flex;
    border: 2px dashed #d9d9d9;
    background-color: #fafafa;
  }
  
  .upload-icon {
    font-size: 36px;
  }
  
  .submit-btn {
    width: 100%;
    height: 40px;
    font-size: 15px;
    margin-top: 40px;
  }
}

@media (max-width: 480px) {
  .avatar-setting-container {
    margin: 10px;
    padding: 10px;
  }
  
  .page-header h2 {
    font-size: 16px;
    padding: 10px 0;
  }
  
  .avatar-content {
    padding: 15px 10px;
  }
  
  .content-layout {
    gap: 15px;
    margin-bottom: 5px;
  }
  
  .right-section {
    display: flex;
    justify-content: center;
    width: 100%;
  }
  
  .upload-box {
    height: 180px;
    display: flex;
    border: 2px dashed #d9d9d9;
    background-color: #fafafa;
  }
  
  .upload-icon {
    font-size: 32px;
  }
  
  .submit-btn {
    height: 38px;
    font-size: 14px;
  }
}
</style>